<?php
namespace App\Admin\Utils;

use App\Models\Order;
use App\Models\Room;
use Illuminate\Support\Facades\DB;

class ChartUtil
{
    public $params = [];
    public function __construct($params = [])
    {
        $this->params = $params;
    }

    public function baseQuery()
    {
        return Order::query()->where('status', Order::STATUS_OVER);
    }
    
    /**
     * 按年统计
     */
    public function byYear()
    {
        # 总数量
        $records = $this->byMonthBaseQuery()->select(DB::raw('count(*) as count, DATE_FORMAT(end_date ,\'%Y\') AS year, sum(days) as days, sum(total_amount) as total_amount'))->groupBy('year')->orderBy('year', 'asc')->get()->toArray();
        $results = [];
        $datas = [];
        for($start_year=2023; $start_year<=date("Y");$start_year++) {
            $record = collect($records)->where('year', $start_year)->first();
            $item = [
                'count' => $record ? $record['count'] : 0,# 年份房间被预订次数
                'year' => $start_year,
                'days' => $record ? $record['days'] : 0, # 年份房间被预订的总天数
                'total_amount' => $record ? $record['total_amount'] : 0, # 年份房间被预订的总价格
                'x_text' => $start_year . '年',
            ];
            array_push($datas, $item);
        }
        $results['datas'] = $datas;
        $results['total'] = collect($datas)->sum('count');
        $results['total_days'] = collect($datas)->sum('days');
        $results['total_amount'] = collect($datas)->sum('total_amount');
        return $results;
    }

    /**
     * 按月份统计
     */
    public function byMonth()
    {
        $params = $this->params;

        // \'%Y-%m\
        $records = $this->byMonthBaseQuery()->select(DB::raw('count(*) as count, DATE_FORMAT(end_date ,\'%c\') AS month, sum(days) as days, sum(total_amount) as total_amount'))->groupBy('month')->orderBy('month', 'asc')->get()->toArray();
        $results = [];
        $year = isset($params['year']) && $params['year'] ? $params['year'] : date("Y");
        $last_month = date("Y") == $year ? date("n") : 12;
        $datas = [];
        for($i=1; $i<=$last_month;$i++) {
            $record = collect($records)->where('month', $i)->first();
            $item = [
                'count' => $record ? $record['count'] : 0, # 这个月房间被预订次数
                'month' => $i,
                'days' => $record ? $record['days'] : 0, # 这个月房间被预订的总天数
                'total_amount' => $record ? $record['total_amount'] : 0, # 这个月房间被预订的总价格
                'x_text' => $i . '月',
            ];
            array_push($datas, $item);
        }
        $results['datas'] = $datas;
        $results['total'] = collect($datas)->sum('count');
        $results['total_days'] = collect($datas)->sum('days');
        $results['total_amount'] = collect($datas)->sum('total_amount');
        return $results;
    }

    public function byMonthBaseQuery()
    {
        $params = $this->params;
        if (isset($params['year']) && $params['year']) {
            $start_date = year_start($params['year']);
            $end_date = year_end($params['year']);
        } else {
            $start_date = year_start(date("Y"));
            $end_date = year_end(date("Y"));
        }
        $base_query = $this->baseQuery()->where('end_date', '>=', $start_date)->where('end_date', '<=', $end_date);
        return $base_query;
    }

    /**
     * 按房间
     */
    public function byRoom()
    {
        $filters = $this->params;
        list($default_start_date, $default_end_date) = $this->getPrevMonth();

        $start_date = isset($filters['room_start_date']) && $filters['room_start_date'] ? $filters['room_start_date'] : '';
        $end_date = isset($filters['room_end_date']) && $filters['room_end_date'] ? $filters['room_end_date'] : $default_end_date;
        if (!$start_date) {
            $start_date = $default_start_date; # 默认从一个月前开始
        }


        $rooms = Room::query()->pluck('number', 'id')->all();
        $records = $this->byRoomBaseQuery($start_date, $end_date)
        ->select(DB::raw('count(*) as count, room_id, sum(days) as days, sum(total_amount) as total_amount'))->groupBy('room_id')->orderBy('room_id', 'asc')->get()->toArray();
        $results = [];
        $datas = [];
        foreach($records as $record) {
            $item = [
                'count' => $record ? $record['count'] : 0,
                'room' => isset($rooms[$record['room_id']]) ? $rooms[$record['room_id']] : '无',
                'days' => $record ? $record['days'] : 0, # 房间被预订的总天数
                'total_amount' => $record ? $record['total_amount'] : 0, # 房间被预订的总价格
                'x_text' => isset($rooms[$record['room_id']]) ? $rooms[$record['room_id']] : '无',
            ];
            array_push($datas, $item);
        }
        $results['datas'] = $datas;
        $results['total'] = collect($datas)->sum('count');
        $results['total_days'] = collect($datas)->sum('days');
        $results['room_start_date'] = $start_date;
        $results['room_end_date'] = $end_date;
        $results['total_amount'] = collect($datas)->sum('total_amount');
        return $results;

    }

    private function byRoomBaseQuery($start_date, $end_date)
    {
        $base_query = $this->baseQuery();
        if ($start_date) {
            $base_query->where('end_date', '>=', $start_date);
        }
        if ($end_date) {
            $base_query->where('end_date', '<=', $end_date);
        }
        return $base_query;
    }

    private function getPrevMonth()
    {
        $current_year = date("Y");
        $current_month = date("n");
        $year = $current_year;
        if ($current_month == 1) {
            $year = $current_year - 1;
            $month = 12;
        } else {
            $month = $current_month-1;
        }
        $last_start_date = date("Y-m-25", strtotime("{$year}-{$month}-01"));
        $last_end_date = now()->toDateString() > date("Y-m-24") ? date("Y-m-24") : now()->toDateString();
        return [$last_start_date, $last_end_date];
    } 
}